# -*- coding: utf-8 -*-
"""
Create Time: 2019/11/13 19:03
Author: yxl
Descript:
"""
import json

from django.http import JsonResponse
from django_redis import get_redis_connection


def get_cart_data(request):
    if request.user:
        redis_cli = get_redis_connection('cart')
        cart_data = redis_cli.get('redis_data_%d'%request.user.id)
        if cart_data:
            cart_data = json.loads(cart_data.decode())

    else:
        cart_data = request.COOKIES.get('cookie_data')
        if cart_data:
            cart_data = json.loads(cart_data)



    return cart_data


def get_all_num(request):
    cart_data = get_cart_data(request)
    all = 0
    if cart_data:
        for gid in cart_data:
            num = int(cart_data[gid]['num'])
            all += num
    return all


def save_cart_data(request,cart_data):
    cart_data = json.dumps(cart_data)
    if request.user:
        redis_cli = get_redis_connection('cart')
        redis_cli.set('redis_data_%d' % request.user.id, cart_data)
        return JsonResponse({'res': 'ok'})
    else:
        res = JsonResponse({'res': 'ok'})
        res.set_cookie('cookie_data', cart_data)
        return res